package com.echoesnet.echoesshortvideo.views;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.Activities.BindPhoneAct;
import com.echoesnet.echoesshortvideo.Activities.CUserInfoAct;
import com.echoesnet.echoesshortvideo.Beans.CommentListBean;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.NetUtil;
import com.echoesnet.echoesshortvideo.Utils.NetUtilListener;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.CommentListViewModel;
import com.echoesnet.echoesshortvideo.views.adapters.CommentListAdapter;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yqh
 * @Date 2018/4/24
 * @Version 1.0
 */
public class CommentListDialog extends DialogFragment implements View.OnClickListener
{
    private final String TAG = CommentListDialog.class.getSimpleName();

    private Activity mActivity;

    private TextView titleCommentNum;
    private TextView dialogContent;
    private UltimateRecyclerView commentList;
    private RelativeLayout titleCancel;
    private LinearLayout commentListBottom;

    private String videoId = "";
    private String videoSenderId = "";

    private CommentListViewModel model;
    private CommentListAdapter adapter;

    private List<CommentListBean.CommentRowsInfo> list = new ArrayList<>();

    private InputTextMsgDialog dialog;

    private int selectPosition;
    private CommentListBean.CommentRowsInfo selectRosInfo;

    @Override
    public void onStart()
    {
        super.onStart();
        Window win = getDialog().getWindow();
        // 一定要设置Background，如果不设置，window属性设置无效
        win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.BOTTOM;
        // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        win.setAttributes(params);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState)
    {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//        View view = LayoutInflater.from(getActivity()).inflate(R.layout.comment_list_dialog, container, false);
        View view = inflater.inflate(R.layout.comment_list_dialog, container, false);
        titleCommentNum = view.findViewById(R.id.titleCommentNum);
        dialogContent = view.findViewById(R.id.dialogContent);
        titleCancel = view.findViewById(R.id.titleCancel);
        commentListBottom = view.findViewById(R.id.commentListBottom);
        commentList = view.findViewById(R.id.commentList);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        afterViews();
    }

    private void afterViews()
    {
        mActivity = getActivity();
        if (getArguments() != null)
        {
            videoId = getArguments().getString("videoId");
            videoSenderId = getArguments().getString("videoSenderId");
        }
        titleCancel.setOnClickListener(this);
        dialogContent.setOnClickListener(this);
        commentListBottom.setOnClickListener(this);

        setUpList();


//        model = ViewModelProviders.of(this).get(CommentListViewModel.class);
        model = new CommentListViewModel();
        model.getCommentListBeanLiveData().observe(this, commentListBean -> {
            if (commentListBean != null)
            {
                titleCommentNum.setText(commentListBean.getTotal());
                list.clear();
                list.addAll(commentListBean.getRows());
                adapter.notifyDataSetChanged();
                commentList.scrollVerticallyToPosition(0);
                if (list.isEmpty())
                    commentList.showEmptyView();
                else
                    commentList.hideEmptyView();
            }
        });
        model.getMoreCommentListBeanLiveData().observe(this, commentListBean -> {
            if (commentListBean != null)
            {
                list.addAll(commentListBean.getRows());
                adapter.notifyDataSetChanged();
                if (list.isEmpty())
                    commentList.showEmptyView();
                else
                    commentList.hideEmptyView();
            }
        });
        model.getLikeComment().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                try
                {
                    String likeOrNot;
                    int likeNum;
                    if ("0".equals(selectRosInfo.getComment().getLikeOrNot()))
                    {
                        likeOrNot = "1";
                        String commentLikeNum = list.get(selectPosition).getComment().getLikeNum();
                        likeNum = Integer.parseInt(commentLikeNum) + 1;
                    }
                    else
                    {
                        likeOrNot = "0";
                        String commentLikeNum = list.get(selectPosition).getComment().getLikeNum();
//                        likeNum = Integer.parseInt(commentLikeNum) - 1;
                        likeNum = Integer.parseInt(commentLikeNum);
                    }
                    list.get(selectPosition).getComment().setLikeOrNot(likeOrNot);
                    list.get(selectPosition).getComment().setLikeNum(String.valueOf(likeNum));
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

                adapter.notifyDataSetChanged();
            }
        });

        model.getDeleteComment().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                model.getCommentList(videoId);
                if (actionListener != null)
                    actionListener.onCommentDelete();
            }
        });

        model.getCommentVideoResult().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                if (dialog != null)
                {
                    dialog.dismiss();
                    ToastUtils.showShort("评论成功");
                    if (actionListener != null)
                        actionListener.onCommentSuccess();
                }
                model.getCommentList(videoId);
            }
        });
        model.getReplyCommentVideoResult().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                if (dialog != null)
                {
                    dialog.dismiss();
                    ToastUtils.showShort("评论成功");
                    if (actionListener != null)
                        actionListener.onCommentSuccess();
                }
                model.getCommentList(videoId);
            }
        });

        model.getCommentList(videoId);
    }

    private void setUpList()
    {
        if (adapter == null)
            adapter = new CommentListAdapter(mActivity, list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        commentList.setLayoutManager(linearLayoutManager);
        commentList.reenableLoadmore();
        commentList.setHasFixedSize(false);
        adapter.setCustomLoadMoreView(LayoutInflater.from(mActivity).inflate(R.layout.bottom_progressbar, null));
        commentList.setAdapter(adapter);


        commentList.hideEmptyView();
        commentList.setEmptyView(R.layout.empty_view_commentlist, UltimateRecyclerView.EMPTY_CLEAR_ALL, new emptyViewOnShownListener()
        {
            @Override
            public void onEmptyViewShow(View mView)
            {
                TextView tvDesc = mView.findViewById(R.id.tvDesc);
                tvDesc.setText("一楼还没有被占领，快评论占领Ta~");
            }
        });
        commentList.setOnLoadMoreListener((itemsCount, maxLastVisiblePosition) -> {
            model.getMoreCommentList(videoId);
        });

        commentList.setDefaultOnRefreshListener(() -> {
            model.getCommentList(videoId);
        });

        adapter.setOnItemClickListener((view, position, commentInfo) -> {
            switch (view.getId())
            {
                case R.id.commentUserHeader:
                    // TODO: 2018/4/25 评论列表头像点击 跳转个人详情
                    Intent intent = new Intent(mActivity, CUserInfoAct.class);
                    intent.putExtra("uId", commentInfo.getComment().getUserId());
                    intent.putExtra("Activity", "Activity");
                    startActivity(intent);
                    break;
                case R.id.llLike:
                    // TODO: 2018/4/25 评论点赞
                    if (CommonUtils.checkUserStateFromFragment(CommentListDialog.this, TAG))
                    {
                        selectPosition = position;
                        selectRosInfo = commentInfo;
                        model.likeComment(commentInfo.getComment().getCommentId());
                    }
                    break;
                case R.id.llCommentContent:
                    if (CommonUtils.checkUserStateFromFragment(CommentListDialog.this, TAG))
                    {
//                        commentList.scrollVerticallyToPosition(position);

                        model.checkVideoState(videoId).observe(CommentListDialog.this, result -> {
                            if (result != null)
                            {
                                if ("0".equals(result.get("result")))
                                {
                                    dialog = new InputTextMsgDialog();
                                    dialog.setCancelable(true);
                                    dialog.setOnInputFinishedListener(inputContent ->
                                    {
                                        if (TextUtils.isEmpty(inputContent))
                                        {
                                            ToastUtils.showShort("请输入评论内容");
                                            return;
                                        }
                                        String commentId;
                                        Map<String, String> userInfo = new HashMap<>();
                                        commentId = commentInfo.getComment().getCommentId();
                                        userInfo.put(commentInfo.getComment().getUserId(), commentInfo.getComment().getNickname());
                                        model.startReplyComment(videoId, inputContent, commentId, userInfo);
                                    });
                                    dialog.show(mActivity.getFragmentManager(), InputTextMsgDialog.class.getSimpleName());
                                    dialog.setInputHint("回复" + commentInfo.getComment().getNickname());
                                }
                                else
                                {
                                    ToastUtils.showShort("该视频已被删除");
                                }
                            }
                        });
                    }

                    break;
            }
        });
        adapter.setOnItemLongClickListener((view, position, commentInfo) -> {
            //视频发送者的ID 或 评论者的ID 和 自己的ID 一致 可删除评论
            if (videoSenderId.equals(SharePreUtils.getUId()) ||
                    commentInfo.getComment().getUserId().equals(SharePreUtils.getUId()))
            {
                selectPosition = position;
                new CustomAlertDialog(mActivity)
                        .builder()
                        .setCancelable(true)
                        .setMsg("确认删除该条评论么？")
                        .setPositiveButton("删除", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                model.deleteComment(commentInfo.getComment().getCommentId());
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {

                            }
                        }).show();
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.titleCancel:
                dismiss();
                break;
            case R.id.dialogContent:
                dismiss();
                break;
            case R.id.commentListBottom:

//                if (actionListener != null)
//                    actionListener.onInputTextClick();
                if (CommonUtils.checkUserStateFromFragment(CommentListDialog.this, TAG))
                {
                    NetUtil.checkIsBindMobile(new NetUtilListener()
                    {
                        @Override
                        public void onSuccess()
                        {
                            model.checkVideoState(videoId).observe(CommentListDialog.this, result -> {
                                if (result != null)
                                {
                                    if ("0".equals(result.get("result")))
                                    {
                                        dialog = new InputTextMsgDialog();
                                        dialog.setCancelable(true);
                                        dialog.setOnInputFinishedListener(inputContent ->
                                        {
                                            if (TextUtils.isEmpty(inputContent))
                                            {
                                                ToastUtils.showShort("请输入评论内容");
                                                return;
                                            }
                                            model.startCommentVideo(videoId, inputContent);
                                        });
                                        dialog.show(mActivity.getFragmentManager(), InputTextMsgDialog.class.getSimpleName());
                                    }
                                    else
                                    {
                                        ToastUtils.showShort("该视频已被删除");
                                    }
                                }
                            });



                        }

                        @Override
                        public void onFail()
                        {
                            new CustomAlertDialog(mActivity)
                                    .builder()
                                    .setCancelable(true)
                                    .setMsg("当前未绑定手机号\n绑定后才可以操作哦\n")
                                    .setPositiveButton("去绑定", v ->
                                    {
                                        Intent intent = new Intent(mActivity, BindPhoneAct.class);
                                        mActivity.startActivity(intent);
                                    })
                                    .setNegativeButton("暂时不绑", v ->
                                    {
                                    }).show();
                        }
                    });
                }

                break;
        }
    }

    private CommentEventActionListener actionListener;

    public void setCommentEventActionListener(CommentEventActionListener listener)
    {
        actionListener = listener;
    }

    public interface CommentEventActionListener
    {
        //        void onTopRightCancelClick();
//        void onBottomCommentClick();
        void onCommentSuccess();

        void onCommentDelete();

    }

}
